package com.share.servlet;

import com.share.domain.UserDomain;
import com.share.domain.UserDomainImpl;
import com.share.entity.User;
import com.share.servlet.utils.ForwardUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by leep on 2015-12-31.
 */
public class RegisterServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/user/register.jsp");
		requestDispatcher.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		String mobile = req.getParameter("mobile");
		User user = new User();
		initUser(userName, password, mobile, user);
		UserDomain userDomain = new UserDomainImpl();
		String msg = userDomain.registerUser(user);
		if (!StringUtils.equals(msg, "成功")) {
			req.setAttribute("msg", msg);
			ForwardUtils.forward(req, resp, "/user/register.jsp", getServletContext());
		} else {
			req.getSession().setAttribute("user", user);
			resp.sendRedirect("/user");
		}

	}

	private void initUser(String userName, String password, String mobile, User user) {
		user.setMobile(mobile);
		user.setName(userName);
		user.setPassword(password);
	}
}
